package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/live/api/request"
	"zg3/live/internal/dao"
	"zg3/live/internal/model"
)

func AddLive(c *gin.Context) {
	var req request.AddLiveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	live := dao.FindLiveName(req.Name)
	if live.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "该直播间已存在",
			"data": nil,
		})
		return
	}
	live = model.Live{
		Name:  req.Name,
		Title: req.Title,
		Brief: req.Brief,
	}
	if !dao.Create(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "创建直播间失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "创建直播间成功",
		"data": live,
	})
	return
}

func InfoLive(c *gin.Context) {
	var req request.InfoLiveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	dao.FindId(req.LiveId, &live)
	if live.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 10000,
		"msg":  "查询直播间成功",
		"data": live,
	})
	return
}

func UpdateLive(c *gin.Context) {
	var req request.UpdateLiveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	dao.FindId(req.LiveId, &live)
	if live.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	live.Name = req.Name
	live.Title = req.Title
	live.Brief = req.Brief

	if !dao.Update(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "更新直播间信息失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "更新直播间信息成功",
		"data": live,
	})
	return
}

func RemoveLive(c *gin.Context) {
	var req request.RemoveLiveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	dao.FindId(req.LiveId, &live)
	if live.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	if !dao.Remove(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "删除直播间失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除直播间成功",
		"data": true,
	})
	return
}
